package com.example.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * 数据源配置
 */
@Configuration //声明配置类
@MapperScan("com.example.mapper")
public class DataSourceConfig implements EnvironmentAware {

    private RelaxedPropertyResolver relaxedPropertyResolver;

    private final Log logger = LogFactory.getLog(getClass());

    @Override
    public void setEnvironment(Environment environment) {
        relaxedPropertyResolver = new RelaxedPropertyResolver(environment, "spring.datasource.");
    }

    @Bean(destroyMethod = "close", initMethod = "init")
    public DataSource injectDataSource() throws SQLException {
        logger.info("注入 druid 数据源 !");
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(relaxedPropertyResolver.getProperty("username"));
        dataSource.setPassword(relaxedPropertyResolver.getProperty("password"));
        dataSource.setUrl(relaxedPropertyResolver.getProperty("url"));
        dataSource.setDriverClassName(relaxedPropertyResolver.getProperty("driver-class-name"));
        //加载链接池配置
        dataSource.setInitialSize(NumberUtils.toInt(relaxedPropertyResolver.getProperty("initialSize")));
        dataSource.setMinIdle(NumberUtils.toInt(relaxedPropertyResolver.getProperty("minIdle")));
        dataSource.setMaxActive(NumberUtils.toInt(relaxedPropertyResolver.getProperty("maxActive")));
        dataSource.setMaxWait(NumberUtils.toLong(relaxedPropertyResolver.getProperty("maxWait")));
        dataSource.setTimeBetweenEvictionRunsMillis(NumberUtils.toLong(relaxedPropertyResolver.getProperty("timeBetweenEvictionRunsMillis")));
        dataSource.setMinEvictableIdleTimeMillis(NumberUtils.toLong(relaxedPropertyResolver.getProperty("minEvictableIdleTimeMillis")));
        dataSource.setValidationQuery(relaxedPropertyResolver.getProperty("validationQuery"));
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(NumberUtils.toInt(relaxedPropertyResolver.getProperty("maxPoolPreparedStatementPerConnectionSize")));
        dataSource.setFilters(relaxedPropertyResolver.getProperty("filters"));
        dataSource.setConnectionProperties(relaxedPropertyResolver.getProperty("connectionProperties"));

        return dataSource;

    }

    //配置sql sessionfactory
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(injectDataSource());

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));

        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager() throws Exception {
        return new DataSourceTransactionManager(injectDataSource());
    }
}
